import { defineStore } from 'pinia'
import { ref } from 'vue'
import { loginAPI } from '@/apis/user'
import { useCartStore } from './carStore'
import { concateCartAPI } from '@/apis/carStore'
export const useUserStore = defineStore('user', () => {
        //1.定义管理用户数据的state
        const userInfo = ref({})
        const carStore = useCartStore()
        //2. 定义获取接口数据的action函数 
        const getUserInfo = async ({ account, password }) => {
                const res = await loginAPI({ account, password })
                userInfo.value = res.result
                //登录之后合并购物车操作
                await concateCartAPI(carStore.carList.map(item => {
                        return {
                                skuId: item.skuId,
                                selected: item.selected,
                                count: item.count
                        }
                }))
                //登录之后获取购物车列表
                carStore.updateNewList()
        }
        //退出时清除我们的用户信息
        const claerUserinfo = () => {
                userInfo.value = {}
                //执行清除购物车的action
                carStore.clearCarStore()
        }
        return {
                userInfo,
                getUserInfo,
                claerUserinfo
        }

},
        {
                persist: true,
        }
)